package main;

import java.awt.Image;
import java.io.File;
import java.io.FilenameFilter;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.ImageIcon;

/**
 * Filter class.
 * 
 * @author kolmas
 * 
 */
class ImageMatcher implements FilenameFilter {

	private String[] imgTypes = { "png", "jpg", "gif", "jpeg" };
	private String regex = "(?<=\\.).*$";

	/* (non-Javadoc)
	 * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String)
	 */
	@Override
	public boolean accept(File file, String fname) {
		
		Matcher matcher = Pattern.compile(regex).matcher(fname);
		if (matcher.find()) {
			String ext = matcher.group();
			for (String type : imgTypes) {
				if (type.equalsIgnoreCase(ext)) {
					return true;
				}
			}
		}
		return false;
	}

}

/**
 * Loads all images from certain directory.
 * 
 * @author kolmas
 * 
 */
public class ImageLoader {

	private static boolean ready = false;
	private final static String DEFAULT_LOC = "images/";
	private static HashMap<String, Image> images = new HashMap<String, Image>();

	private final String src = "src/";
	private static int totalImg = 0;
	private static int currentImg = 0;
	
	public ImageLoader() {
		this(DEFAULT_LOC);
	}

	public ImageLoader(String folder) {
		loadImages(folder);
	}

	/**
	 * Loads all images from certain folder.
	 * 
	 * @param folder
	 */
	public void loadImages(String folder) {
		File dir = new File(src + folder);
		File[] files = dir.listFiles(new ImageMatcher());
		
		totalImg = files.length;

		// Fillin the hashmap.
		for (File f : files) {
			images.put(f.getName(), new ImageIcon(f.getAbsolutePath())
					.getImage());
			currentImg++;
		}

		// After everything is done let's call ourself ready!
		ready = true;
		System.out.println("ImageLoader finished loading images! Loaded ("
				+ images.size() + ") images.");
	}

	/**
	 * Get certain image
	 * 
	 * @param fname
	 * @return
	 */
	public static Image getImage(String fname) {
		if (!isReady())
			return null;
		Image tmp = images.get(fname);
		if (tmp == null)
			System.err.println("Cant find image: " + fname);
		return tmp;
	}

	/**
	 * Are images loaded?
	 * 
	 * @return
	 */
	public static boolean isReady() {
		return ready;
	}
	
	public static int getTotal() {
		return totalImg;
	}
	
	public static int getCurrent() {
		return currentImg;
	}
}
